package yl.hs.bmipfull.service.material.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IPurchaseContractDao;
import yl.hs.bmipfull.pojo.material.PurchaseContractEntity;
import yl.hs.bmipfull.pojo.material.PurchaseContractProductEntity;
import yl.hs.bmipfull.pojo.material.PurchaseReceiptEntity;
import yl.hs.bmipfull.pojo.material.RawMaterialInfoEntity;
import yl.hs.bmipfull.service.material.IPurchaseContractProductService;
import yl.hs.bmipfull.service.material.IPurchaseContractService;
import yl.hs.bmipfull.service.material.IPurchaseReceiptService;
import yl.hs.bmipfull.service.material.IRawMaterialInfoService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作用:  采购合同信息服务层接口实现<br/>
 * 创建时间: 2021年05月19日 15时30分07秒 <br/>
 *
 * @author 吴高丰
 */
@Service
public class PurchaseContractServiceImpl extends PurchaseBaseService implements IPurchaseContractService {

    @Autowired
    IPurchaseContractDao dao;
    @Autowired
    IRawMaterialInfoService rawService;
    @Autowired
    IPurchaseContractProductService contractProductService;
    @Autowired
    IPurchaseReceiptService receiptService;
    @Override
    public List<PurchaseContractEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(PurchaseContractEntity.class);
        return dao.queryList(pageQuery.getQuery());
    }

    @Override
    public PageResult<Object> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(PurchaseContractEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        pageQuery.getQuery().put("unitSNArray", getCompanySNList());
        PageResult<Object> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),PurchaseContractEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(),filters));
        result.setPage(page);
        List<Object> ss = new ArrayList<>();
        var data= dao.queryPage(pageQuery.getQuery(),filters);
        data.forEach(t->{
            var map = t.toMap();
            var product = contractProductService.queryListByContractSn(t.getSn());
            map.put("product",contractProductService.queryListByContractSn(t.getSn()));
            map.put("ship",receiptService.queryListByContractSn(t.getSn()));
            ss.add(map);
        });
        result.setData(ss);
        return result;
    }

    @Override
    public PageResult<PurchaseContractEntity> queryPages(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(PurchaseContractEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        pageQuery.getQuery().put("unitSNArray", getCompanySNList());
        PageResult<PurchaseContractEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),PurchaseContractEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(),filters));
        result.setPage(page);
        var data= dao.queryPage(pageQuery.getQuery(),filters);
        result.setData(data);
        return result;
    }


    @Override
    public PurchaseContractEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional
    public Integer savePurchaseContract(Map<String, Object> model, String sn, List<PurchaseContractProductEntity> dates) throws Exception {
        Integer result = 0;
        PurchaseContractEntity entity;
        if (Tl.isEmpty(sn)) {
            //执行保存
            entity = new PurchaseContractEntity();
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(PurchaseContractEntity.class));
            entity.setOrganizationCode(getDepartSN());
            //产品明细设值
            dates = setPurchaseContractProduct(dates, entity.getSn());
            entity.setPriceSet(dates.stream().filter(s->s.getPrice()==0).count()==0);
            //拼接采购明细产品名称
            entity.setProducts(SplicingProducts(dates));
            result = dao.insertNew(entity);
            if (result > 0) {
                //插入产品明细信息
                insertPurchaseContractProduct(dates, entity.getSn());
                writeLog(ActionType.CREATE, entity.getSn(), "插入采购合同信息信息", Tl.toJson(entity), PurchaseContractEntity.class);
            }

        } else {
            //执行修改
            entity = findBySn(sn);
            var backJson = entity.toJson();
            var changeLog = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            //产品明细设值
            dates = setPurchaseContractProduct(dates, entity.getSn());
            //拼接采购明细产品名称
            entity.setProducts(SplicingProducts(dates));
            entity.setPriceSet(dates.stream().filter(s->s.getPrice()==0).count()==0);
            result = dao.update(entity);
            if (result > 0) {
                //插入产品明细信息
                insertPurchaseContractProduct(dates, entity.getSn());
                writeLog(ActionType.UPDATE, sn, changeLog, backJson, PurchaseContractEntity.class);
            }
        }
        if (result > 0) {
            saveGS(
                    entity.getSn(),
                    entity.getContractName(),
                    String.join(",",
                            entity.getContractName(),
                            entity.getSupplierName(),
                            entity.getLinker(),
                            entity.getPurchaser(),
                            entity.getLinkPhone(),
                            entity.getProducts(),
                            entity.getRemark()
                    ),
                    entity,
                    HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                    entity.getOrganizationCode()
            );
        }
        return result;
    }

    /**
     * 添加合同产品信息
     *
     * @param dates      合同产品信息
     * @param contractSn 合同编号
     * @return 受影响行数
     */
    public Integer insertPurchaseContractProduct(List<PurchaseContractProductEntity> dates, String contractSn) throws Exception {
        Integer result = 0;
        if (dates != null && dates.size() > 0 && dates.get(0) != null) {
            result = contractProductService.savePurchaseContractProduct(dates, contractSn);
        }
        return result;
    }

    /**
     * 给合同产品明细设值
     *
     * @param dates      合同产品明细
     * @param contractSn 合同编号
     * @return 合同产品明细
     */
    public List<PurchaseContractProductEntity> setPurchaseContractProduct(List<PurchaseContractProductEntity> dates, String contractSn) {
        if (dates != null && dates.size() > 0 && dates.get(0) != null) {
            try {
                for (PurchaseContractProductEntity entity : dates) {
                    RawMaterialInfoEntity rawEntity = rawService.findBySn(entity.getRmSN());
                    if (rawEntity != null) {
                        entity.setBrand(rawEntity.getBrand());
                        entity.setRmName(rawEntity.getRmName());
                        entity.setRmSpec(rawEntity.getRmSpec());
                    }
                    entity.setContractSn(contractSn);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return dates;
    }

    /**
     * 拼接产品明细名称
     *
     * @param dates 产品明细信息
     * @return 拼接产品名称
     */
    public String SplicingProducts(List<PurchaseContractProductEntity> dates) {
        String strPro = null;
        for (PurchaseContractProductEntity item : dates) {
            if (strPro != null && !strPro.equals("")) {
                strPro = strPro + ";" + item.getRmName() + item.getRmSpec();
            } else {
                strPro = item.getRmName() + item.getRmSpec();
            }

        }
        return strPro;
    }


    @Transactional
    public Integer delete(String[] sn) {
        var result = dao.changeStateBySn(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, PurchaseContractEntity.class);
            deleteGs(sn);
        }
        return result;
    }

    @Override
    public List<PurchaseContractEntity> querySupplierSn(String supperlierSN) {
        return dao.querySupplierSn(supperlierSN);
    }

    @Override
    public Integer changeStateBySn(String[] snArray, short state) {
        int result=dao.changeStateBySn(snArray,state);
        if (result > 0) {
            forWriteLog(snArray,state);
        }
        return result;
    }
}